<?php


namespace app\common\model\settings;

use app\common\library\sms\Driver as SmsDriver;
use app\common\model\BaseModel;
use app\common\model\settings\Setting as SettingModel;
use app\common\model\customer\Customer;
use app\common\exception\BaseException;

/**
 * 短信模型
 */
class Sms extends BaseModel
{
    protected $pk = 'sms_id';
    protected $name = 'sms';

    /**
     * 短信发送
     */
    public function send($data)
    {
        if ($data['type'] == 'login') {//验证用户信息
            Customer::validate($data);
        }
        $smsConfig = SettingModel::getItem('sms', 10001);
        $template_code = $smsConfig['engine'][$smsConfig['default']]['template_code'];
        if (empty($template_code)) {
            $this->error = '短信登录未开启';
            return false;
        }
        $code = str_pad(mt_rand(100000, 999999), 6, "0", STR_PAD_BOTH);
        $SmsDriver = new SmsDriver($smsConfig);
        $send_data = [
            'code' => $code
        ];

        //短信模板
        $flag = $SmsDriver->sendSms($data['mobile'], $template_code, $send_data);
        if ($flag) {
            $this->save([
                'mobile' => $data['mobile'],
                'code' => $code,
                'app_id' => 10001
            ]);
        }
        return $flag;
    }

    /**
     * 验证
     */
    public function check($data)
    {
        //判断验证码是否过期、是否正确
        $sms_record_list = $this
            ->where('mobile', '=', $data['mobile'])
            ->order(['create_time' => 'desc'])
            ->limit(1)->select();

        if (count($sms_record_list) == 0) {
            throw new BaseException(['msg' => '未查到短信发送记录']);
        }
        $sms_model = $sms_record_list[0];
        if ((time() - strtotime($sms_model['create_time'])) / 60 > 30) {
            throw new BaseException(['msg' => '短信验证码超时']);
        }
        if ($sms_model['code'] != $data['code']) {
            throw new BaseException(['msg' => '验证码不正确']);
        }
        return true;
    }

}